package org.example.util;

import java.nio.ByteBuffer;
import java.time.LocalDateTime;

public class ProcessorUtil {

    public static byte[] encodeTimestamp(LocalDateTime timestamp) {
        ByteBuffer buffer = ByteBuffer.allocate(5);

        // 获取年份的后两位，将其转换为byte
        int year = timestamp.getYear() % 100;
        byte byteYear = (byte) year;

        // 获取月份，并转换为byte
        byte byteMonth = (byte) timestamp.getMonthValue();

        // 获取日期，并转换为byte
        byte byteDay = (byte) timestamp.getDayOfMonth();

        // 获取小时，并转换为byte
        byte byteHour = (byte) timestamp.getHour();

        // 获取分钟，并转换为byte
        byte byteMinute = (byte) timestamp.getMinute();

        // 依次将各个byte添加到buffer中
        buffer.put(byteYear);
        buffer.put(byteMonth);
        buffer.put(byteDay);
        buffer.put(byteHour);
        buffer.put(byteMinute);

        // 将buffer中的数据转换为byte数组并返回
        return buffer.array();
    }


    // 计算校验位（异或和）
    public static byte calculateChecksum(byte[] data, int startIndex, int endIndex) {
        byte checksum = 0;
        for (int i = startIndex; i < endIndex; i++) {
            checksum ^= data[i];
        }
        return checksum;
    }

    // 判断两个字节数组是否相等
    private static boolean byteArrayEquals(byte[] array1, byte[] array2) {
        if (array1.length != array2.length) {
            return false;
        }
        for (int i = 0; i < array1.length; i++) {
            if (array1[i] != array2[i]) {
                return false;
            }
        }
        return true;
    }

    // 字节数组转十六进制字符串
    public static String byteArrayToHexString(byte[] data) {
        StringBuilder sb = new StringBuilder();
        for (byte b : data) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString().trim();
    }

    // 十六进制字符串转字节数组
    private static byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll("\\s", "");
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

    public static int hexToDecimal(String hexString) {
        int decimal = 0;
        for (int i = 0; i < hexString.length(); i++) {
            char hexChar = hexString.charAt(i);
            int hexValue = Character.digit(hexChar, 16);
            decimal = decimal * 16 + hexValue;
        }
        return decimal;
    }
}
